package com.alisonyu.spider.Downloader;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yuzhiyi
 * @date 2018/7/19 14:55
 */
public class BrowserUtil {

    public static WebDriver getPhantomJs() {
        String osname = System.getProperties().getProperty("os.name");
        if (osname.equals("Linux")) {//判断系统的环境win or Linux
            System.setProperty("phantomjs.binary.path", "/usr/bin/phantomjs");
        } else {
            String path = BrowserUtil.class.getResource("/phantomjs.exe").getPath();
            System.out.println(path);
            System.setProperty("phantomjs.binary.path", path);//设置PhantomJs访问路径
        }
        DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
        //设置参数
        desiredCapabilities.setCapability("phantomjs.page.settings.userAgent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 　　Firefox/50.0");
        return null;
    }

    public static WebDriver getChrome(){
        String path = BrowserUtil.class.getResource("/chromedriver.exe").getPath();
        System.out.println(path);
        System.setProperty("webdriver.chrome.driver", path);//设置Chrome访问路径
        ChromeOptions chromeOptions = new ChromeOptions();
        //TODO 整合到配置中,让用户可以指定Chrome的路径
        chromeOptions.setBinary("C:\\Users\\yu\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
//      设置为 headless 模式 （必须）
        chromeOptions.addArguments("test-type"); //ignore certificate errors
        chromeOptions.addArguments("headless");// headless mode
        chromeOptions.addArguments("disable-gpu");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        Map<String, Object> prefs = new HashMap<String, Object>();
//        prefs.put("profile.default_content_settings.popups", 0);
        //http://stackoverflow.com/questions/28070315/python-disable-images-in-selenium-google-chromedriver
        prefs.put("profile.managed_default_content_settings.images",2); //禁止下载加载图片
        chromeOptions.setExperimentalOption("prefs", prefs);
        caps.setJavascriptEnabled(true);
        caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//        caps.setCapability("takesScreenshot", false);
        WebDriver driver = new ChromeDriver(caps);
        return driver;
    }



}
